<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 13-9-29
 * Time: 下午1:49
 * 日库存设置
 * $s = array(
    array(
    'pid'=>'',//
    'bt'=>'',//开始时间
    'et'=>'',//结束时间
    'p1'=>'',//供货价
    'p2'=>'',//零售价
    'ptype'=>0,//价格类型（0平日1周末2特殊）
    'rid'=>'',//记录ID[修改状态下需要],
    'ondays'=>'',//星期,
    'storage'=>'',//库存量
    )
    );
 */
include 'common/autoload.php';
include 'common/errBack.php';
include 'class/Price.class.php';
include 'module/link_product/function.php';
$soap = SoapInit::GetSoapInside();

write_logs($_SESSION['memberID'].json_encode($_REQUEST));
function write_logs($txt,$file=''){
	if($file=='') $file = '/var/www/html/new/d/logs/cache_logs/daily_storage_'.$_SESSION['sid'].date('_Y-m-d').'.txt';
	$fp = fopen($file,"a");
	flock($fp, LOCK_EX);
	fwrite($fp,date("Y-m-d H:i:s").":".$txt."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}


// 删除配置
if(isset($_POST['act']) && $_POST['act']=='clear'){
	$pid    = $_POST['pid'];
	$params = json_decode($_POST['params'], true);
	if(count($params)==0) exit('{"errcode":1007,"msg":"请选择删除日期"}');
	foreach($params as $row) if($row['rid']>0) $delBox_a[] =  $row['rid'];
	$delSize = count($delBox_a);
	if(!$delSize) exit('{"errcode":1007,"msg":"您选择的日期不存在配置"}'); 
	$sql = "delete from uu_product_price where id in (".implode(',', $delBox_a).") and pid=$pid limit $delSize";
	$txt = ($GLOBALS['le']->query($sql)) ? '{"errcode":100,"msg":"删除成功！"}':'{"errcode":1007,"msg":"删除失败，请重试"}';
	$GLOBALS['le']->close();
	exit($txt);
	exit;
}




/**
 * 总库存设置
 *  total_storage
 *  storage_open
 *  tid
 *  pid
*/
if(!empty($_POST['total_storage'])) {
    $s = $_POST['total_storage'] < -1 || !is_numeric($_POST['total_storage']) ?
        exit('{"errcode":1007,"msg":"总库存必须为大于等于-1的数字！"}')
        :$_POST['total_storage'];
    $t = !checkData($_POST['storage_open'])
            ?exit('{"errcode":1007,"msg":"库存启用日期格式错误"}')
            :$_POST['storage_open'];
    $res = Price::SetTotalStorage(
        $GLOBALS['le'],
        $s,
        $t,
        abs($_POST['tid']),
        abs($_POST['pid'])
    );
    if($res) {
        echo '{"errcode":100,"msg":"总库存设置成功！"}';
    }
    else{
        echo '{"errcode":1007,"msg":"总库存设置失败！"}';
    }
}
//日库存设置
else {
    $pid = abs($_POST['pid']);
    //TODO::查询此产品是否同步到分销平台（16u.cc）
    $sql_get_fxpid = "SELECT pft_rflex_id,sync_status,sync_id FROM uu_jq_ticket WHERE pid=$pid LIMIT 1";
    $GLOBALS['le']->query($sql_get_fxpid);
    $sync_data = $GLOBALS['le']->fetch_assoc();
    $fx_pid = $GLOBALS['le']->f('pft_rflex_id');

    if($fx_pid>0) {
        $soapFX = SoapInit::GetSoapFX();
    }

    $daily_storage = json_decode($_POST['params'], true);
    if(!count($daily_storage)) {
        exit('{"errcode":1007,"msg":"提交数据为空，无法保存。"}');
    }

    $memo = '';
	$package = getMainId($pid, 2);// 是否有套票

	if(count($package)) {
		$flag = true;
		$hashMd = array();// 修改的产品容器
		$Price = new Price(-1);
		$packPris = array();// 获取套票的月份内的价格
		$nums = array();
		foreach($package as $k => $v){
			$arr = array(
				'orderMonth'=> substr($daily_storage[0]['st'], 0, 7),
				'pid'=>$k,
				'timer'=>time()
			);
			$packPris[$k] = json_decode(raw_post('http://www.12301.cc/call/calenda_price.php',$arr), true);
			$tp = explode('|',$v);
			$nums[$k] = $tp[1] ;
		}
		$isUpper = false;
		// 获取打包
	}
    foreach($daily_storage as $post) {
        $ptype = abs($post['ptype']);
        $startdate = !empty($post['st']) && checkData($post['st']) ? $post['st']
            : exit('{"errcode":1007,"msg":"起始日期格式错误！'.$post['bt'].'"}');
        $enddate = !empty($post['et']) && checkData($post['et']) ? $post['et']
            : exit('{"errcode":1007,"msg":"结束日期格式错误！"}');
        if(strtotime($post['bt'])>strtotime($post['et'])) {
            exit('{"errcode":1007,"msg":"结束日期不能小于开始日期"}');
        }
        $ondays ='0,1,2,3,4,5,6';
        $pg = abs($post['p1'])*100;//供货价
        $pl = abs($post['p2'])*100;//零售价
        $rid = abs($post['rid']);
        if($pl < $pg) {
            exit( '{"errcode":1007,"msg":"零售价不能小于供货价！"}' );
        }
        if( !is_numeric($post['storage']) ) {
            $storage = -1;
        }
        else{
            $storage = $post['storage'];
        }
        if( $storage<-1) {
            exit('{"errcode":1007,"msg":"日库存只能为大于等于“-1”的数字！"}');
        }
		
		if($flag){ // 获取差价
			// $date = date('Y-m-d');
			// echo "GetDynamicPrice($startdate, 1, $startdate, $enddate, 0, 0, $pid)";
			$ori=($Price->GetDynamicPrice($startdate, 1, $startdate, $enddate, 0, 0, $pid));
			$diff = $post['p1'] - $ori/100;// 相比上次的价钱
			// echo $startdate,$enddate;
		}
        //echo $storage;
        $res = Price::DynamicPriceStatic($pid, $startdate, $enddate, $pg, $pl,
                        $ptype, $rid, $memo, $ondays, $soap, $storage,
                        $sync_data['pft_rflex_id'], null,false, $sync_data['sync_id'],
                        $sync_data['sync_status']);//100 ok
        if($res!=100) {
            exit('{"errcode":1007,"msg":"'
                .$post['st'].'的配置发生错误！错误信息:'.$SoapRequestChk[$res].'"}');
        }
	
		if($flag){// 供货价上调，修改套票的价格
			$isUpper = true;
			// echo $startdate,$enddate;
			if($diff > 0){
				foreach($package as $v=>$txt){
					if(count($packPris[$v]['pricelists'])){// 如果存在
						if(isset($packPris[$v]['pricelists'][$startdate])){// 这一天也有设置
							$packOriSpri = $packPris[$v]['pricelists'][$startdate]['sprice'];
							$packOriLpri = $packPris[$v]['pricelists'][$startdate]['lprice'];
							$targetSpri = ($packOriSpri + $diff * $nums[$v])*100;
							$targetLpri = ($packOriLpri + $diff * $nums[$v])*100;
							$packRid = $packPris[$v]['pricelists'][$startdate]['uid'] ? 
							$packPris[$v]['pricelists'][$startdate]['uid']:0;
							// echo "DynamicPriceStatic($v, $startdate, $enddate, $targetSpri, $targetLpri, $ptype, $packRid, $memo, $ondays, , $storage, $fx_pid, )<br/>";
							Price::DynamicPriceStatic($v, $startdate, $enddate, $targetSpri, $targetLpri, $ptype, $packRid, $memo, $ondays, $soap, $storage, $fx_pid, $soapFX);
							$hashMd[] = $v;
						}
					}
				}
			}
		}
    }
	if(count($hashMd) && $isUpper){// 发送通知给套票供应商
		include_once 'class/notice.class.php';
		include_once 'class/MemberAccount.class.php';
		$notice = new pft\notice();
		$ids = implode(',',$hashMd).','.abs($_POST['pid']);
		$sql="SELECT p_name,apply_did,id FROM uu_products WHERE id IN ($ids)";
		$GLOBALS['le']->query($sql);
		$pinfo = array();
		while($row=$GLOBALS['le']->fetch_assoc()){
			$pinfo[$row['id']]=$row;
		}
		foreach($pinfo as $k => $v){
			if($k==$pid) continue;
			$debug = <<<h
			AddNotice(
				'套票价格上调',
				'您的套票产品【{$v['p_name']}】由于子票【{$pinfo[$pid]['p_name']}】价格上调，系统自动上调套票价格，如果不想上调，请自行设置',
				1,
				9999,
				1,
				0,
				'',
				'',
				\pft\Member\MemberAccount(, {$v['apply_did']}, ),
				{$v['apply_did']}
			)
h;
			// echo $debug;
			// print_r(
			$notice->AddNotice(
				'套票价格上调',
				'您的套票产品【'.$v['p_name'].'】由于子票【'.$pinfo[$pid]['p_name'].'】价格上调，系统自动上调套票价格，如果不想上调，请自行设置',
				1,
				9999,
				1,
				0,
				'',
				'',
				new \pft\Member\MemberAccount($GLOBALS['le'], $v['apply_did'], $soap),
				$v['apply_did']
			);
			// );
		}
		// print_r($pinfo);
	}
	
    echo '{"errcode":100,"msg":"配置成功"}';
}
function raw_post($url,$data){
	$ch = curl_init(); 
	curl_setopt($ch, CURLOPT_POST, 1); 
	curl_setopt($ch, CURLOPT_HEADER, 0); 
	curl_setopt($ch, CURLOPT_URL,$url); 
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	return curl_exec($ch);
}